import { PathDTO, ServiceProxy, SiteDTO, WarehouseDTO } from './../../../../shared/service-proxy/service-proxies';
import { Component, OnInit, ViewChild, ElementRef, Injector } from '@angular/core';
import { AppComponentBase } from '@shared/common/app-component-base';
import { FormBuilder, FormGroup, Validators } from '@angular/forms';

@Component({
  selector: 'app-set-path-modal',
  templateUrl: './set-path-modal.component.html',
  styleUrls: ['./set-path-modal.component.less']
})
export class SetPathModalComponent extends AppComponentBase implements OnInit {
  isVisible: boolean = false;
  isOkLoading: boolean = false;
  model: PathDTO = new PathDTO();
  companyList: WarehouseDTO[] = [];
  startCompanyList: WarehouseDTO[] = [];
  endCompanyList: WarehouseDTO[] = [];
  sites: SiteDTO[] = [];

  validateForm: FormGroup;
  constructor(injector: Injector,
    private fb: FormBuilder,
    private _service: ServiceProxy) {
    super(injector);
  }

  ngOnInit() {
    this.validateForm = this.fb.group({
      startSiteId: [null, [Validators.required]],
      endSiteId: [null, [Validators.required]],
      startWarehouseId: [null, [Validators.required]],
      endWarehouseId: [null, [Validators.required]],
      pathNo: [null, [Validators.required]],
      defaultFlag: [null, [Validators.required]],
    });

    this.getAllSites();
    this.getAllCompany();
  }

  getAllSites() {
    this._service.getAllSitesUsingGET().subscribe(result => {
      this.sites = result.result.fieldList;
    });
  }

  getAllCompany() {
    this._service.getAllWarehouseDTOsUsingGET().subscribe(result => {
      this.companyList = result.result.fieldList;
    });
  }

  getCompanyForStart() {
    this.startCompanyList = this.companyList.filter(m => m.siteId == this.model.startWarehouseId);
  }

  getCompanyForEnd() {
    this.endCompanyList = this.companyList.filter(m => m.siteId == this.model.endWarehouseId);
  }

  show(): void {
    this.isVisible = true;
  }

  handleOk(): void {
    this.isOkLoading = true;
    for (const i in this.validateForm.controls) {
      this.validateForm.controls[i].markAsDirty();
      this.validateForm.controls[i].updateValueAndValidity();
    }

    if (this.validateForm.valid) { // 验证通过
     
      this._service.createPathUsingPOST(this.model).subscribe(result=>{
        this.isOkLoading = false;
        if(result.success)
        {
          this.message.success(this.l('save_success'));
          this.isVisible = false;
        }
        else{
          this.message.info(this.l(result.error.message));
        }
       
      }, error => {
        this.isOkLoading = false;
        this.message.error(this.l(error.message));
      });
    }
    else { // 验证未通过
      this.isOkLoading = false;
      this.message.error(this.l('verify_failed_please_check_the_form_item'));
    }


  }
  handleCancel() {
    this.isVisible = false;
  }
}
